//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package wudashan.test;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.coap.Response;
import org.eclipse.californium.core.coap.CoAP.ResponseCode;
import org.eclipse.californium.core.coap.CoAP.Type;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.Endpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.eclipse.californium.core.server.resources.Resource;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig.Builder;
import org.eclipse.californium.scandium.dtls.cipher.CipherSuite;
import org.eclipse.californium.scandium.dtls.pskstore.PskStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TupClient {
    private static final Logger logger = LoggerFactory.getLogger(TupClient.class);
    private TupClient.DeviceResource resource;
    private CoapServer server;
    private boolean isSecure = false;

    public TupClient(boolean isSecure) {
        this.isSecure = isSecure;
    }

    private CoapEndpoint getServerEndpoint() {
        if (this.isSecure) {
            Builder builder = new Builder(new InetSocketAddress(5684));
            builder.setPskStore(new TupClient.TupClientPskStore());
            builder.setSupportedCipherSuites(new CipherSuite[]{CipherSuite.TLS_PSK_WITH_AES_128_CCM_8, CipherSuite.TLS_PSK_WITH_AES_128_CBC_SHA256});
            DTLSConnector connector = new DTLSConnector(builder.build());
            return new CoapEndpoint(connector, NetworkConfig.getStandard());
        } else {
            return new CoapEndpoint(5683, NetworkConfig.getStandard());
        }
    }

    public void start() {
        this.server = new CoapServer();
        this.server.addEndpoint(this.getServerEndpoint());
        CoapResource rootResource = new CoapResource("t");
        this.resource = new TupClient.DeviceResource("d");
        rootResource.add(this.resource);
        this.server.add(new Resource[]{rootResource});
        this.server.start();
        InetSocketAddress inetSocketAddress = ((Endpoint)this.resource.getEndpoints().get(0)).getAddress();
        logger.info("TupClient CoAP server start. {}:{}", inetSocketAddress.getAddress().getHostAddress(), inetSocketAddress.getPort());
    }

    public void stop() {
        this.server.destroy();
    }

    public void register(String ep) {
        logger.info("process Register for {}", ep);
        org.eclipse.californium.core.CoapClient.Builder builder = new org.eclipse.californium.core.CoapClient.Builder("100.101.73.50", this.isSecure ? 5684 : 5683);
        CoapClient coapClient = builder.query("ep=" + ep).path(new String[]{"t", "r"}).create();
        coapClient.setEndpoint(this.server.getEndpoints().get(0));
        CoapResponse response = coapClient.post("", 42);
        logger.info("process Register done, response is {}", response.getCode());
    }

    public void uploadMoData(String data) {
        logger.info("notify changed :{}", data);
        this.resource.stateChanged(data);
    }

    public void uploadMoData(byte[] data) {
        logger.info("notify changed :{}", new String(data));
        this.resource.stateChanged(data);
    }

    public static void main(String[] args) {
        TupClient client = new TupClient(true);
        client.start();
        client.register("0123456789");
        client.startLoop();
    }

    void startLoop() {
        while(true) {
            this.uploadMoData("1234");

            try {
                Thread.sleep(5000L);
            } catch (InterruptedException var2) {
            }
        }
    }

    public static class TupClientPskStore implements PskStore {
        public TupClientPskStore() {
        }

        public byte[] getKey(String identity) {
            return "0123456789".getBytes();
        }

        public String getIdentity(InetSocketAddress inetAddress) {
            return "0123456789";
        }
    }

    public static class DeviceResource extends CoapResource {
        private byte[] data = null;

        public DeviceResource(String name) {
            super(name);
            this.setObservable(true);
            this.getAttributes().setTitle("Observable resource");
            this.getAttributes().addResourceType("observe");
            this.getAttributes().setObservable();
            this.setObserveType(Type.CON);
        }

        public void handleGET(CoapExchange exchange) {
            try {
                TupClient.logger.info("handle GET from {}:{} ", exchange.getSourceAddress(), exchange.getSourcePort());
                Response response = new Response(ResponseCode.CONTENT);
                if (null != this.data) {
                    TupClient.logger.info("response GET :{}", new String(this.data));
                    response.setPayload(this.data);
                }

                this.data = null;
                exchange.respond(response);
            } catch (RuntimeException var3) {
                var3.printStackTrace();
                throw var3;
            }
        }

        public void handlePOST(CoapExchange exchange) {
            try {
                TupClient.logger.info("receive POST from {}:{}:\n{} ", exchange.getSourceAddress(), exchange.getSourcePort(), exchange.advanced().getRequest());
                String payload = new String(exchange.getRequestPayload(), StandardCharsets.UTF_8);
                TupClient.logger.info("POST payload is {}", payload);
                exchange.respond(ResponseCode.CONTENT);
            } catch (RuntimeException var3) {
                var3.printStackTrace();
                throw var3;
            }
        }

        public void setPayload(String payload) {
            if (null == payload) {
                this.data = null;
            } else {
                this.data = payload.getBytes();
            }

        }

        public void stateChanged(String payload) {
            this.setPayload(payload);
            this.changed();
        }

        public void stateChanged(byte[] payload) {
            this.data = payload;
            this.changed();
        }
    }
}
